package com.fengshang.wedding.web.view;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.web.servlet.View;
/**
 * 
 *@author gembin@gmail.com
 * 
 */
public class ModuleView implements View {
	private static Logger logger=Logger.getLogger(ModuleView.class);
	public static final String MODULE_DATA= "module.data";
	private static final String CONTENT_TYPE = "application/json; charset=UTF-8";
	private static final String ERROR= "error";
	public String getContentType() {
		return CONTENT_TYPE;
	}
	
	private Map getErrorMessage(String message){
		Map<String,String> messageData=new HashMap<String,String>();
		messageData.put(ERROR, message);
		return messageData;
	}

	@SuppressWarnings("unchecked")
	public void render(Map model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.debug("render ModuleView...");
		Object data = model.get(MODULE_DATA);
		JSONObject object =null;
		if(data!=null){
			if(data instanceof Map){
				object = new JSONObject((Map)data);   
			}else{
				object = new JSONObject(getErrorMessage("Wrong data object type,expect java.util.Map, but was "+data.getClass()));   
				logger.warn("Wrong data object type,expect java.util.Map, but was "+data.getClass());
			}
		}else{
			object = new JSONObject(getErrorMessage("No Data available"));   
			logger.warn("No Data available");
		}
		 
		logger.debug("json: " + object.toString());
		response.setCharacterEncoding("utf-8");   
		response.setHeader("Pragma", "no-cache");   
        response.setHeader("Cache-Control", "no-cache, must-revalidate");   
        response.setHeader("Pragma", "no-cache");  
		response.getWriter().write(object.toString());

	}

}
